<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <i class="el-icon-document"></i>
        <span style="margin-left: 8px; font-weight: bold;">停车记录详情</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-spinner></el-spinner>
        <div>加载中...</div>
      </div>
      
      <div v-else>
        <el-row :gutter="40" style="padding: 30px 0;">
          <el-col :span="14">
            <div style="font-size: 16px; margin-bottom: 10px;">
              <span style="background: #f56c6c; color: #fff; border-radius: 12px; padding: 2px 12px; margin: 0 10px;">{{ recordDetail.plateNumber || '未识别' }}</span>
              <el-tag :type="recordDetail.vehicleType === 1 ? 'success' : 'warning'">
                {{ recordDetail.vehicleType === 1 ? '月租车' : '临时车' }}
              </el-tag>
              <el-tag :type="recordDetail.status === 0 ? 'primary' : 'info'" style="margin-left: 10px">
                {{ recordDetail.status === 0 ? '在场' : '离场' }}
              </el-tag>
            </div>
            <div style="margin-bottom: 8px;">车主：{{ recordDetail.ownerName || '未知' }}</div>
            <div style="margin-bottom: 8px;">手机号：{{ recordDetail.ownerPhone || '未知' }}</div>
            <div style="margin-bottom: 8px;">入场时间：{{ formatDate(recordDetail.startTime) }}</div>
            <div style="margin-bottom: 8px;">出场时间：{{ recordDetail.endTime ? formatDate(recordDetail.endTime) : '未离场' }}</div>
            <div style="margin-bottom: 8px;" v-if="recordDetail.endTime">停放时长：{{ calculateDuration(recordDetail.startTime, recordDetail.endTime) }}</div>
            <div style="margin-bottom: 8px;" v-if="recordDetail.fee">停车费用：{{ recordDetail.fee }}元</div>
            <div style="margin-bottom: 8px;" v-if="recordDetail.doPay !== undefined">
              支付状态：
              <el-tag :type="recordDetail.doPay === 1 ? 'success' : 'danger'">
                {{ recordDetail.doPay === 1 ? '已支付' : '未支付' }}
              </el-tag>
            </div>
            <div style="margin-bottom: 8px;">停车场ID：{{ recordDetail.parkingId || '未知' }}</div>
            <div style="margin-bottom: 8px;" v-if="recordDetail.orderId">订单号：{{ recordDetail.orderId }}</div>
          </el-col>
          <el-col :span="10" style="text-align: center;">
            <div v-if="images.length > 0" class="image-container">
              <el-carousel :interval="4000" type="card" height="200px">
                <el-carousel-item v-for="(img, index) in images" :key="index">
                  <img :src="img.imgsrc" alt="车辆照片" 
                     style="width: 100%; height: 100%; object-fit: cover; border-radius: 6px;" />
                </el-carousel-item>
              </el-carousel>
              <div style="margin-top: 10px; color: #888;">车辆照片</div>
            </div>
            <div v-else>
              <img :src="defaultImg" alt="无照片" 
                   style="width: 220px; height: 140px; object-fit: cover; border-radius: 6px; border: 1px solid #eee;" />
              <div style="margin-top: 10px; color: #888;">暂无车辆照片</div>
            </div>
          </el-col>
        </el-row>
        
        <el-divider></el-divider>
        
        <div class="action-buttons" v-if="recordDetail.status === 0">
          <el-button type="primary" @click="handleExit">模拟车辆离场</el-button>
        </div>
        
        <div class="action-buttons" v-if="recordDetail.status === 1 && recordDetail.doPay === 0">
          <el-button type="success" @click="handlePay">支付停车费</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ParkingRecordDetail',
 
  data() {
    return {
      recordId: '',
      recordDetail: {},
      images: [],
      loading: true,
      defaultImg: ''
    }
  },
  created() {
    // 从路由参数获取ID
    this.recordId =  this.$route.query.id;
    console.log('recordId:', this.recordId)
    if (this.recordId) {
      this.fetchRecordDetail()
    } else {
      this.$message.error('记录ID不能为空')
      this.loading = false
    }
  },
  methods: {
    // 获取记录详情
    fetchRecordDetail() {
      this.loading = true
      
      // 获取基本信息
      axios.get('/api/vehicle-server/record/queryByRecordId/'+this.recordId)
        .then(response => {
          if (response.data.code === 200) {
            this.recordDetail = response.data.data
            // 获取照片信息
            this.fetchRecordImages()
          } else {
            this.$message.error(response.data.msg || '获取记录详情失败')
            this.loading = false
          }
        })
        .catch(error => {
          console.error('获取记录详情失败', error)
          this.$message.error('获取记录详情失败')
          this.loading = false
        })
    },
    
    // 获取记录相关的图片
    fetchRecordImages() {
      axios.get('/api/vehicle-server/record/queryImagesByRecordId/'+this.recordId)
        .then(response => {
          if (response.data.code === 200) {
            this.images = response.data.data || []
            console.log('images:', this.images)
          } else {
            console.warn('获取图片失败:', response.data.msg)
          }
        })
        .catch(error => {
          console.error('获取图片失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    },
    // 计算停车时长
    calculateDuration(startTime, endTime) {
      if (!startTime || !endTime) return '-'
      
      const start = new Date(startTime)
      const end = new Date(endTime)
      const diff = Math.abs(end - start) / 1000 // 差值（秒）
      
      const days = Math.floor(diff / 86400)
      const hours = Math.floor((diff % 86400) / 3600)
      const minutes = Math.floor((diff % 3600) / 60)
      
      let result = ''
      if (days > 0) result += `${days}天`
      if (hours > 0) result += `${hours}小时`
      if (minutes > 0) result += `${minutes}分钟`
      
      return result || '不足1分钟'
    },
    // 返回上一页
    goBack() {
      this.$router.push({
        path: '/parking-record'
      });
    },
    // 处理车辆离场
    handleExit() {
      this.$confirm('确定要模拟车辆离场吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post(`/api/vehicle/simulateExit`, this.recordId)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('车辆离场成功')
              this.fetchRecordDetail()
            } else {
              this.$message.error(response.data.msg || '操作失败')
            }
          })
          .catch(error => {
            console.error('操作失败', error)
            this.$message.error('操作失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    // 处理支付
    handlePay() {
      this.$confirm('确定要支付停车费吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post(`/api/vehicle/payOrder`, this.recordDetail.orderId)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success('支付成功')
              this.fetchRecordDetail()
            } else {
              this.$message.error(response.data.msg || '支付失败')
            }
          })
          .catch(error => {
            console.error('支付失败', error)
            this.$message.error('支付失败')
          })
      }).catch(() => {
        // 取消操作
      })
    }
  }
}
</script>

<style scoped>
.el-card {
  margin: 20px 0;
}
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}
.action-buttons {
  text-align: center;
  margin-top: 20px;
}
.image-container {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}
</style> 